package LeetCode;

import java.util.Deque;
import java.util.LinkedList;

public class Code394_decodeString {
    // 栈
    public String decodeString(String s) {
        if (s == null || s.length() == 0){
            return "";
        }
        Deque<Integer> multi_stack = new LinkedList<>();
        Deque<String> res_stack = new LinkedList<>();
        StringBuilder res = new StringBuilder();
        char[] chars = s.toCharArray();
        int multi = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= '0' && chars[i] <= '9'){
                multi = multi * 10 + Integer.parseInt(chars[i] + "");
            } else if (chars[i] >= 'a' && chars[i] <= 'z'){
                res.append(chars[i]);
            } else if (chars[i] == '['){
                // 入栈
                multi_stack.push(multi);
                multi = 0;
                res_stack.push(res.toString());
                res = new StringBuilder();
            } else if (chars[i] == ']'){
                int num = multi_stack.pop();
                StringBuilder temp = new StringBuilder();
                for (int j = 0; j < num; j++) {
                    temp.append(res);
                }
                res = new StringBuilder(res_stack.pop() + temp);
            } else {
                res.append(chars[i]);
            }
        }
        return res.toString();
    }

    public static void main(String[] args) {
        //String s = "3[a2[c]]";
        //String s = "3[a]2[bc]";
        String s = "100[leetcode]";
        Code394_decodeString code394_decodeString = new Code394_decodeString();
        System.out.println(code394_decodeString.decodeString(s));
    }
}
